package com.lyj.friend.service.user.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyj.common.core.constants.Constants;
import com.lyj.common.core.domain.TableDataInfo;
import com.lyj.common.core.enums.ExamListType;
import com.lyj.common.core.enums.ResultCode;
import com.lyj.common.core.utils.ThreadLocalUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyj.friend.domain.exam.Exam;
import com.lyj.friend.domain.exam.dto.ExamQueryDTO;
import com.lyj.friend.domain.exam.vo.ExamVO;
import com.lyj.friend.domain.user.UserExam;
import com.lyj.friend.manager.ExamCacheManager;
import com.lyj.friend.mapper.exam.ExamMapper;
import com.lyj.friend.mapper.user.UserExamMapper;
import com.lyj.friend.service.user.UserExamService;
import com.lyj.security.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-09-08
 * Time: 15:54
 */
@Service
public class UserExamServiceImpl implements UserExamService {
    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Override
    public int enter(String token, Long examId) {
        //判断竞赛是否存在
        Exam exam = examMapper.selectById(examId);
        if(exam == null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        //竞赛未开赛
        if(exam.getStartTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }

        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        //判断是否已经存在关系
        UserExam userExam = userExamMapper.selectOne(new QueryWrapper<UserExam>().lambda()
                .eq(UserExam::getExamId,examId)
                .eq(UserExam::getUserId,userId));
        if(userExam != null){
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        examCacheManager.addUserExamCache(userId, examId);
        //添加到数据库
        userExam = new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);

    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        //首先查询redis中的数据
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);
        List<ExamVO> examVOList = new ArrayList<>();
        //查询不到访问数据库
        if(total == null || total <= 0){
            PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            //将数据添加到redis中
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
            total = new PageInfo<>(examVOList).getTotal();
        }else {
            //redis中存在数据
            examVOList = examCacheManager.getExamVOList(examQueryDTO, userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(), userId);
        }
        if(examVOList == null){
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList,total);

    }
}
